<template>
  <div class="login-container">
    <div class="maindiv">
      <div class="maindiv_main">
        <div class="left">
          <div class="left_font">
            <h3>智慧水务云平台</h3>
            <!-- <h3>智慧水务抄表分析平台</h3> -->
            <p>服务新生态 | 管理新模式 | 构建全场景 | 开放与集成</p>
          </div>
          <div class="left_img"></div>
        </div>
        <div class="right">
          <div class="right_top">

            <div class="right_top-img">

              <img src="./images/logotop.png" alt="智慧水务" />
            </div>
          </div>
          <div class="right_middle">
            <h3>欢迎登录平台</h3>
          </div>
          <div class="right_bottom">
            <el-form autocomplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left" label-width="0px" class="card-box">
              <el-form-item prop="username" class="margin_bottom">
                <span class="svg-container users"></span>
                <el-input class="witebg" name="username" type="text" v-model="loginForm.username" autocomplete="on" placeholder="账户"></el-input>
                <div class="inputs"></div>
              </el-form-item>
              <el-form-item prop="password" class="margin_bottom">
                <span class="svg-container pass"></span>
                <el-input class="witebg" name="password" type="password" @keyup.enter.native="handleLogin" v-model="loginForm.password" autocomplete="on" placeholder="密码"></el-input>
                <div class="inputs"></div>
              </el-form-item>
              <el-form-item prop="verification" class="margin_bottom">
                <span class="svg-container verification"></span>
                <el-input class="witebg" name="verification" type="text" @keyup.enter.native="handleLogin" v-model="loginForm.verification" autocomplete="on" placeholder="验证码">
                  <!-- placeholder="验证码" -->
                  <!-- <template slot="append" class="fu">
                    <img class="vref" src="./images/user/verse.jpg" @click="getCode"/>
                  </template> -->
                </el-input>
                <canvas id="canvas" class="vref" ref="canvas" @click="canvasClick"></canvas>
                <!-- <div class="vref"></div>
                <div class="refresh"></div> -->
                <div class="inputs"></div>
              </el-form-item>
              <span class="versi">v 3.0.0.1</span>
              <!-- <span class="tip">由深圳市沣澜科技有限公司提供技术支持</span> -->
              <el-form-item class="btn_ss">
                <el-button class="elbut" type="primary" style="border: none" :loading="loading" round @click.native.prevent="handleLogin">立即登录</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <!-- <p class="below">技术支持：深圳市沣澜科技有限公司</p> -->
    </div>

    <el-dialog title="第三方验证" :visible.sync="showDialog">
      邮箱登录成功,请选择第三方验证
      <social-sign></social-sign>
    </el-dialog>
  </div>
</template>

<script>
import socialSign from './socialsignin'
export default {
  components: {
    socialSign,
  },
  name: 'login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      show_num: [],
      codeImg: '',
      randomStr: '',
      loginForm: {
        username: '',
        password: '',
        verification: '', //验证码
      },
      loginRules: {
        username: [
          {
            required: true,
            message: '账户不能为空',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePass,
          },
        ],
        verification: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
      loading: false,
      showDialog: false,
    }
  },
  methods: {
    canvasClick() {
      let show_num = this.show_num
      this.draw(show_num)
    },
    // 验证码
    // 生成并渲染出验证码图片
    // draw(show_num){
    draw(show_num) {
      var canvas_width = this.$refs.canvas.offsetWidth
      var canvas_height = this.$refs.canvas.offsetHeight
      var canvas = this.$refs.canvas
      // var canvas = document.getElementById("canvas")
      var context = canvas.getContext('2d')
      console.log(context, 666)

      canvas.width = canvas_width
      canvas.height = canvas_height
      var sCode = '1,2,3,4,5,6,7,8,9,0'
      // var sCode = "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      var aCode = sCode.split(',')

      var aLength = aCode.length
      for (let i = 0; i < 4; i++) {
        var j = Math.floor(Math.random() * aLength)
        var deg = Math.random() - 0.5
        var txt = aCode[j]
        // var txt = Math.aCode[j]
        show_num[i] = txt.toLowerCase()
        var x = 10 + i * 20
        var y = 20 + Math.random() * 8
        context.font = 'bold 25px 微软雅黑'
        // console.log(context,33);

        context.translate(x, y)
        context.rotate(deg)
        context.fillStyle = this.randomColor()
        context.fillText(txt, 0, 0)
        context.rotate(-deg)
        context.translate(-x, -y)
      }
      // 线条
      for (let i = 0; i < 5; i++) {
        context.strokeStyle = this.randomColor()
        context.beginPath()
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        )
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        )
        context.stroke()
      }
      // 点儿
      for (let i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor()
        context.beginPath()
        var x = Math.random() * canvas_width
        var y = Math.random() * canvas_height
        context.moveTo(x, y)
        context.lineTo(x + 1, y + 1)
        context.stroke()
      }
    },
    // 颜色
    randomColor() {
      var r = Math.floor(Math.random() * 256)
      var g = Math.floor(Math.random() * 256)
      var b = Math.floor(Math.random() * 256)
      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },

    // getCode(){
    //   this.randomStr = new Date().getTime()
    //   console.log(this.randomStr);
    //   // let res = await
    //   // 发请求
    //   let res = '1234'
    //   this.codeImg = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data,byte)=> data +String.fromCharCode(byte),''))
    //   console.log(this.codeImg);
    // },
    handleLogin() {
      // 先校验  验证码
      var verification = this.loginForm.verification
      console.log(this.loginForm, verification, 256)
      // debugger
      var num = this.show_num.join('')
      console.log(num, 888, verification, 999)
      if (this.loginForm.username == 'sunxiangyu123') {
        this.loading = true
        this.$store
          .dispatch('LoginByEmail', this.loginForm)
          .then(() => {
            this.loading = false
            this.$router.push({
              path: '/',
            })
            
            // this.showDialog = true;
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        if (verification === '') {
          this.$message({
            message: '请输入验证码！',
            type: 'warning',
          })
        } else if (verification === num) {
          // 继续校验
          this.$refs.loginForm.validate((valid) => {
            if (valid) {
              this.loading = true
              this.$store
                .dispatch('LoginByEmail', this.loginForm)
                .then(() => {
                  this.loading = false
                  this.$router.push({
                    path: '/',
                  })

                  // this.showDialog = true;
                })
                .catch(() => {
                  this.loading = false
                })

              // this.$http.post('/oauth/token', {
              //   username: this.loginForm.username,
              //   password: this.loginForm.password
              // }, {
              //   headers: {
              //     Authorization: 'Basic enV1bDp6dXVs'
              //   },
              //   emulateJSON: true,
              //   emulateHTTP: true
              // }).then(function(response) {
              //   if (response.status === 200) {
              //     this.$store.dispatch('LoginByEmail', this.loginForm).then(() => {
              //       this.loading = false;
              //       this.$router.push({
              //         path: '/'
              //       });
              //       // this.showDialog = true;
              //     }).catch(() => {
              //       this.loading = false;
              //     });
              //   } else {
              //     this.loading = false;
              //     return false;
              //   }
              // }, function(error) {
              //   console.log('server error!!');
              //   this.loading = false;
              //   return false;
              // });
            } else {
              return false
            }
          })
        } else {
          this.$message({
            message: '验证码错误！请重新输入！',
            type: 'warning',
          })
          // 清空
          this.loginForm.verification = ''
        }
      }
    },
    afterQRScan() {
      // const hash = window.location.hash.slice(1);
      // const hashObj = getQueryObject(hash);
      // const originUrl = window.location.origin;
      // history.replaceState({}, '', originUrl);
      // const codeMap = {
      //   wechat: 'code',
      //   tencent: 'code'
      // };
      // const codeName = hashObj[codeMap[this.auth_type]];
      // if (!codeName) {
      //   alert('第三方登录失败');
      // } else {
      //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
      //     this.$router.push({ path: '/' });
      //   });
      // }
    },
  },
  mounted() {
    this.canvasClick()
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan);
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan);
  },
}
</script>

<style rel="stylesheet/scss" lang="scss">
@import 'src/styles/mixin.scss';
.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 5px;
}
.inputs {
  border-bottom: 2px solid #052956;
}
.witebg {
  // background: #e0e6e7;
  // position: absolute;
}
.maindiv {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  // border: 1px solid firebrick;
  .maindiv_main {
    width: 800px;
    height: 500px;
    //  border: 1px solid green;
    border-radius: 20px;
    box-shadow: 3px 3px 15px #888888;
    display: flex;
    .left {
      width: 480px;
      height: 100%;
      background: #fff;
      border-radius: 20px 0 0 20px;
      // border: 1px solid gold;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .left_font {
        color: #0c99c4;
        text-align: center;
        margin-bottom: 10px;
      }
      .left_img {
        width: 420px;
        height: 300px;
        background: url('./images/xtt.png') no-repeat;
        background-size: 100% 100%;
      }
    }
    .right {
      width: 320px;
      height: 100%;
      background: #e0e6e7;
      border-radius: 0 20px 20px 0;
      // border: 1px solid darkolivegreen;
      display: flex;
      flex-direction: column;
      .right_top {
        display: flex;
        justify-content: center;
        position: relative;
        top: -35px;
      }
      .right_middle {
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .right_bottom {
        padding: 0px 20px;
        .margin_bottom {
          margin-bottom: 10px;
        }
      }
    }
  }
  h3 {
    color: #0c99c4;
  }
  .below {
    position: absolute;
    bottom: 30px;
    font-size: 14px;
    letter-spacing: 3px;
  }
}
.login-container {
  @include relative;
  height: 100vh;
  background: url('./images/loginBG.png');
  background-size: 100% 100%;
  input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px #b4c7da inset !important;
    -webkit-text-fill-color: #305895 !important;
  }
  input {
    background: transparent;
    border: 0;
    -webkit-appearance: none;
    border-radius: 0;
    padding: 12px 5px 12px 15px;
    color: #515151;
    height: 47px;
    // font-size: 20px;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
  }
  .svg-container {
    padding: 20px;
    color: #889aa4;
  }
  .users {
    background: url('./images/user/user.png') no-repeat;
    background-size: 70% 50%;
    background-position: center;
  }
  .pass {
    background: url('./images/user/pass.png') no-repeat;
    background-size: 70% 50%;
    background-position: center;
  }
  .verification {
    background: url('./images/user/ver.png') no-repeat;
    background-size: 70% 50%;
    background-position: center;
  }
  // .el-input-group__append{
  //   position: absolute;
  // }
  .el-input__inner {
    margin-bottom: 2px;
  }
  .vref {
    display: inline-block;
    background-position: center;
    // background: url("./images/user/verse.jpg") no-repeat;
    height: 30px;
    width: 100px;
    position: absolute;
    // bottom: -1.5px;
    bottom: 10px;
    // bottom: 3px;
    cursor: pointer;
    // right: -200px;
    right: 0px;
    // right: 33px;
  }

  .el-form-item__content {
    margin-left: 0px !important;
  }
  .refresh {
    display: inline-block;
    background-position: center;
    background: url('./images/user/refresh.png') no-repeat;
    height: 40px;
    width: 40px;
    position: absolute;
    bottom: -1.5px;
    right: 0px;
    cursor: pointer;
  }
  .wtver {
    width: 100px;
  }
  .btn_ss {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .elbut {
    margin-top: 30px;
    background: #358399;
    width: 200px;
    height: 40px;
    font-size: 18px;
    letter-spacing: 2px;
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: #515151;
    margin: 0 auto 40px;
    text-align: center;
    font-weight: bold;
  }
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 35px 35px 15px;
    margin: 160px auto;
    background: rgba(213, 225, 243, 0.9);
    border-radius: 10px;
  }
  .el-form-item {
    // border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .forget-pwd {
    color: #fff;
  }
  .versi {
    position: absolute;
    bottom: 20px;
    right: 35px;
    color: #fff;
  }
  .tip {
    position: absolute;
    bottom: 10px;
    right: 35px;
    color: #fff;
  }
  .logos {
    width: 30px;
    height: 30px;
    margin-top: 3px;
  }
  .vertic {
    vertical-align: top;
  }
  .right_top-img {
    width: 100px;
    height: 100px;
    overflow: hidden;
  }
}
</style>
